package com.example.a79273.shandianban.fragment;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.a79273.shandianban.DesignerInfoActivity;
import com.example.a79273.shandianban.R;
import com.example.a79273.shandianban.SearchActivity;
import com.example.a79273.shandianban.ShopingCarActivity;
import com.example.a79273.shandianban.WebActivity;
import com.example.a79273.shandianban.YouLiaoActivity;
import com.example.a79273.shandianban.adapter.YouRenListAdapter;
import com.example.a79273.shandianban.adapter.YouRenPagerAdapter;
import com.example.a79273.shandianban.application.MyApplication;
import com.example.a79273.shandianban.config.NetConfigYouRen;
import com.example.a79273.shandianban.model.YouRenBean;
import com.example.a79273.shandianban.model.YouRenIndexBean;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.HttpManager;
import org.xutils.ImageManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * "有人"页面
 */
public class YouRen extends Fragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, ViewPager.OnPageChangeListener {

    private static final String TAG = "YouRen";

    private ViewPager pages_vp;
    private LinearLayout points_ll;
    private ImageView youLiao_iv, shopCar_iv, search_iv;
    private RadioGroup subtitles_rg;
    private PullToRefreshListView designers_lv;
    private ImageView goBackToTop_iv;


    private ImageView point_iv;
    private View headerView;


    private YouRenPagerAdapter pagerAdapter;
    private YouRenListAdapter listAdapter;

    private HttpManager httpManager;
    private ImageManager imageManager;
    private FragmentManager fragmentManager;

    private MyDialogFragment dialogFragment;


    private List<YouRenBean.DataBean.ListBean> listData;
    private List<ImageView> pagerData;

    private String[] titles, titles_en;

    private List<YouRenIndexBean.DataBean.BannerlistBean> bannerlist;

    private int currentPosition = 0;
    private ListView lv;
    private Callback.Cancelable cancelable;

    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_youren, null);
        initView(view);
        initData();
        setData();
        setListener();
        return view;
    }

    private void setListener() {
        subtitles_rg.setOnCheckedChangeListener(this);
        youLiao_iv.setOnClickListener(this);
        pages_vp.addOnPageChangeListener(this);
        goBackToTop_iv.setOnClickListener(this);
        designers_lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData(currentPosition);
                designers_lv.setRefreshing(true);
            }
        });
    }

    private void setData() {
        designers_lv.setAdapter(listAdapter);
        pages_vp.setAdapter(pagerAdapter);
    }

    private void initData() {

        httpManager = x.http();
        imageManager = x.image();
        fragmentManager = getChildFragmentManager();
        dialogFragment = new MyDialogFragment();
/*请求viewpager的数据*/
        pagerData = new ArrayList<>();
        pagerAdapter = new YouRenPagerAdapter(pagerData);

        httpManager.get(new RequestParams(NetConfigYouRen.PAGES_URL), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    YouRenIndexBean indexBean = YouRenIndexBean.objectFromData(MyApplication.dealWithString(result));
                    if (indexBean != null) {
                        bannerlist = indexBean.getData().getBannerlist();

                        points_ll.setWeightSum(bannerlist.size());
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                        params.setMargins(5, 0, 5, 0);
                        for (YouRenIndexBean.DataBean.BannerlistBean banner : bannerlist) {
                            //动态创建圆点
                            point_iv = new ImageView(getActivity());
                            point_iv.setImageResource(R.drawable.point);
                            point_iv.setLayoutParams(params);
                            points_ll.addView(point_iv);

                            final ImageView imageView = new ImageView(getActivity());
                            imageView.setOnClickListener(YouRen.this);
                            pagerData.add(imageView);

                            imageManager.bind(imageView, NetConfigYouRen.ROOT_URL + banner.getPic_scr(), new CommonCallback<Drawable>() {
                                @Override
                                public void onSuccess(Drawable result) {
                                    Log.d(TAG, "onSuccess: ===" + result);
                                    if (result != null) {
                                        imageView.setImageDrawable(result);
                                    }
                                    if (pagerData.size() == bannerlist.size()) {
                                        pagerAdapter.notifyDataSetChanged();
                                        pages_vp.setCurrentItem(1);
                                        point_iv = null;
                                        pointChange(0);
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    Toast.makeText(getActivity(), "网络错误,请检查网络", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onCancelled(CancelledException cex) {

                                }

                                @Override
                                public void onFinished() {

                                }
                            });
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        Resources resources = getActivity().getResources();
        titles = resources.getStringArray(R.array.youRenPageTitles);
        titles_en = resources.getStringArray(R.array.youRenPageTitles_EN);


        for (int i = 0; i < subtitles_rg.getChildCount(); i++) {
            RadioButton subtitle_rb = (RadioButton) subtitles_rg.getChildAt(i);
            subtitle_rb.setText(titles[i]);
            if (i == 0) {
                subtitle_rb.setTextColor(Color.BLACK);
            } else {
                subtitle_rb.setTextColor(Color.GRAY);
            }
        }

        listData = new ArrayList<>();
        listAdapter = new YouRenListAdapter(getActivity(), listData);
        loadData(0);


    }


    private void initView(View view) {
        shopCar_iv = (ImageView) view.findViewById(R.id.iv_youRen_shopCar);
        search_iv = (ImageView) view.findViewById(R.id.iv_youRen_search);
        designers_lv = (PullToRefreshListView) view.findViewById(R.id.lv_youren_designers);
        headerView = View.inflate(getActivity(), R.layout.headerview_youren, null);
        goBackToTop_iv = (ImageView) view.findViewById(R.id.iv_youRen_goBackToTop);

        pages_vp = (ViewPager) headerView.findViewById(R.id.vp_youRen_pagesContainer);
        points_ll = (LinearLayout) headerView.findViewById(R.id.ll_youRen_points);
        youLiao_iv = (ImageView) headerView.findViewById(R.id.iv_youRen_youLiao);
        subtitles_rg = (RadioGroup) headerView.findViewById(R.id.rg_youren_subtitles);

        lv = designers_lv.getRefreshableView();
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        headerView.setLayoutParams(params);
        lv.addHeaderView(headerView);
        designers_lv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);

    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {
            RadioButton child = (RadioButton) group.getChildAt(i);
            if (child.getId() == checkedId) {
                child.setTextColor(Color.BLACK);
                loadData(i);
            } else {
                child.setTextColor(Color.GRAY);
            }

        }
    }

    /*下载数据*/
    public void loadData(int checkedPosition) {
        if (checkedPosition != currentPosition) {
            dialogFragment.show(fragmentManager, "dialog");
            if (!cancelable.isCancelled()) {
                cancelable.cancel();
                if (designers_lv.isRefreshing()) {
                    designers_lv.onRefreshComplete();
                }
            }
        }
        currentPosition = checkedPosition;
        listData.clear();
        String url = String.format(NetConfigYouRen.YOUREN_URL, titles_en[checkedPosition]);
        cancelable = httpManager.get(new RequestParams(url), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    YouRenBean pageBean = YouRenBean.objectFromData(MyApplication.dealWithString(result));
                    if (pageBean != null) {
                        listData.addAll(pageBean.getData().getList());
                        listAdapter.notifyDataSetChanged();
                        if (designers_lv.isRefreshing()) {
                            designers_lv.onRefreshComplete();
                        }
                    }
                }
                if (dialogFragment.isVisible()) {
                    dialogFragment.dismiss();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "网络错误,请检查网络", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v != null) {
            switch (v.getId()) {
                case R.id.iv_youRen_youLiao:
                    startActivity(new Intent(getActivity(), YouLiaoActivity.class));
                    break;
                case R.id.iv_youRen_goBackToTop:

                    int distance = headerView.getTop();
                    lv.smoothScrollBy(distance, 500);
                    break;
                case R.id.iv_youRen_shopCar:
                    startActivity(new Intent(getActivity(), ShopingCarActivity.class));
                    break;
                case R.id.iv_youRen_search:
                    startActivity(new Intent(getActivity(), SearchActivity.class));
                    break;
                default:
                    if (bannerlist != null && bannerlist.size() != 0) {
                        YouRenIndexBean.DataBean.BannerlistBean bannerlistBean;
                        String pic_text;
                        int index = pagerData.indexOf(v);
                        bannerlistBean = bannerlist.get(index);
                        pic_text = bannerlistBean.getPic_text().trim();
                        String pic_id = bannerlistBean.getPic_id().trim();
                        Intent intent = null;
                        switch (pic_text) {
                            case "-1":
                                break;
                            case "0":
                                intent = new Intent(getActivity(), DesignerInfoActivity.class);
                                intent.putExtra("designerId", pic_id);
                                break;
                            case "5":
                                intent = new Intent(getActivity(), WebActivity.class);
                                intent.putExtra("pic_id", pic_id);
                                break;
                        }
                        startActivity(intent);
                    }
                    break;
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pointChange(position);
    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void pointChange(int position) {
        for (int i = 0; i < points_ll.getChildCount(); i++) {
            View child = points_ll.getChildAt(i);
            if (i == position) {
                child.setEnabled(true);
            } else {
                child.setEnabled(false);
            }

        }
    }
}
